import 'dart:convert';
import 'dart:math';
import 'dart:typed_data';

import 'package:bot_toast/bot_toast.dart';
import 'package:crypto/crypto.dart';
import 'package:dio/dio.dart' as dio;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:toolbox/manager/hive/hiveHelper.dart';
import 'package:toolbox/manager/net/networkHelper.dart';
import 'package:toolbox/manager/tools.dart';
import 'package:toolbox/models/TranslateModel.dart';
import 'package:toolbox/widgets/defaultDialog.dart';

import 'translate_state.dart';

class TranslateLogic extends GetxController {
  final TranslateState state = TranslateState();

  @override
  void onInit() {
    super.onInit();
    getHistory();
  }

  @override
  void onClose() {
    state.controller.dispose();
    state.focusNode.dispose();
    state.fromController.dispose();
    state.toController.dispose();
  }

  void onTap() {
    FocusManager.instance.primaryFocus?.unfocus();
  }

  void swap() {
    Languages temp = state.from.value;
    state.from.value = state.to.value;
    state.to.value = temp;
    updateSelectForm();
  }

  Languages? getLanguage(String name) {
    try {
      return Languages.values.byName(name);
    } catch (e) {
      return null;
    }
  }

  void onFromSelected(Languages? selected) {
    if (selected == null) return;
    state.from.value = selected;
  }

  void onToSelected(Languages? selected) {
    if (selected == null) return;
    state.to.value = selected;
  }

  Future<void> translate() async {
    if (state.isSelecting) return;
    onTap();
    state.isSelecting = true;
    const url = 'https://fanyi-api.baidu.com/api/trans/vip/translate';
    const String appId = '20240716002101074';
    const key = '4samrrqqLTIVTDCmVuqu';
    final salt = Random().nextInt(100).toString();

    String q = state.controller.text;

    Uint8List content = const Utf8Encoder().convert(appId + q + salt + key);
    final sign = md5.convert(content).toString();
    Map<String, dynamic> data = {
      'appid': appId,
      'sign': sign,
      'q': q,
      'from': state.from.value.name,
      'to': state.to.value.name,
      'salt': salt,
    };
    BotToast.showLoading();
    dio.Response result = await HttpUtil.getInstance().get(
      url,
      data: data,
      // options: Options(contentType: 'application/x-www-form-urlencoded'),
    );
    BotToast.closeAllLoading();
    print(result);
    state.isSelecting = false;
    if (result.statusCode == 200) {
      TranslateModel model = TranslateModel.fromMap(result.data);
      model.query = q;
      model.searchTime = DateTime.now().millisecondsSinceEpoch;
      if (!model.success) {
        state.result.value = (code[model.errorCode ?? '-1']) ?? '';
        cleanAutoTip();
        return;
      }
      if (state.to.value == Languages.auto ||
          state.from.value == Languages.auto) {
        if (model.to != null && model.from != null) {
          state.autoTo.value = getLanguage(model.to ?? '')?.zhName ?? '';
          state.autoFrom.value = getLanguage(model.from ?? '')?.zhName ?? '';
          update([state.getBuilderIdLanguagesTip]);
        } else {
          cleanAutoTip();
        }
      } else {
        cleanAutoTip();
      }
      HiveHelper.instance.saveTranslateHistory(model);
      state.result.value = model.result ?? '';
      getHistory();
    } else {
      state.result.value =
          result.statusMessage ?? (result.statusCode ?? 'error').toString();
      cleanAutoTip();
    }
  }

  void cleanAutoTip() {
    state.autoTo.value = '';
    state.autoFrom.value = '';
    update([state.getBuilderIdLanguagesTip]);
  }

  void onTapDeleteInput() {
    state.controller.text = '';
  }

  void onTapClearHistory() {
    Get.dialog(defaultDialog(
      content: '确定要清除历史记录吗？',
      sureFunction: () {
        HiveHelper.instance.cleanTranslateHistory();
        state.history.value = [];
      },
    ));
  }

  void getHistory() {
    state.history.value = HiveHelper.instance.getAllTranslateHistory();
  }

  void onTapHistory(TranslateModel model) {
    state.controller.text = model.query ?? '';
    state.from.value = getLanguage(model.from ?? 'auto') ?? Languages.auto;
    state.to.value = getLanguage(model.to ?? 'auto') ?? Languages.auto;
    updateSelectForm();
  }

  void updateSelectForm() {
    state.fromController.text = state.from.value.zhName;
    state.toController.text = state.to.value.zhName;
  }

  void onTapCopy() {
    copyText(state.result.value);
  }
}
